
Public Class LastFM
    Dim sessionID As String = ""
    Dim npURL As String = ""
    Dim submissionURL As String = ""
    Public Function CreateMD5(ByVal myString As String) As String
        Dim md5Obj As New Security.Cryptography.MD5CryptoServiceProvider
        Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(myString)
        bytesToHash = md5Obj.ComputeHash(bytesToHash)
        Dim strResult As String = ""
        For Each b As Byte In bytesToHash
            strResult += b.ToString("x2")
        Next
        Return strResult
    End Function
    Public Function Handshake(ByVal user As String, ByVal passMD5 As String) As String
        ' Prepare request
        Dim timestamp = Int(DateTime.UtcNow.Subtract(#1/1/1970#).TotalSeconds)
        Dim authToken As String = CreateMD5(passMD5 & timestamp)

        ' Make the request
        '' NOTE: Please do NOT use the nva client id if you have modified the source code ''
        Dim handshakeRequest As System.Net.WebRequest = System.Net.WebRequest.Create("http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=nva&v=" & Application.ProductVersion & "&u=" & user & "&t=" & timestamp & "&a=" & authToken)

        ' Get the response
        Dim handshakeResponse As System.IO.Stream = handshakeRequest.GetResponse.GetResponseStream
        Dim readStream As New System.IO.StreamReader(handshakeResponse, System.Text.Encoding.GetEncoding("utf-8"))
        Dim handshakeResponseText As String = readStream.ReadToEnd()

        ' Parse the response
        Dim handshakeResponseArray As Array = handshakeResponseText.Split(Chr(10))
        Select Case handshakeResponseArray(0)
            Case "BANNED"
                MsgBox("This client is using an invalid protocol version. Please upgrade the client to the latest version.")
                Return False
            Case "BADAUTH"
                MsgBox("Invalid Username/Password combination")
                Return False
            Case "BADTIME"
                MsgBox("Your System Time is too inaccurate. Please correct your system time before continuing.")
                Return False
            Case "OK"
                sessionID = handshakeResponseArray(1)
                npURL = handshakeResponseArray(2)
                submissionURL = handshakeResponseArray(3)
                Return True
            Case Else
                MsgBox("Unknown error." & Chr(10) & "Server returned message: " & handshakeResponseArray(1))
                Return False
        End Select
        Return False
    End Function
    Public Function NowPlaying(ByVal trackName As String, ByVal artist As String, Optional ByVal album As String = "", Optional ByVal length As String = "", Optional ByVal trackNumber As String = "")

        ' Make a request
        Dim npRequest As System.Net.WebRequest = System.Net.WebRequest.Create(npURL)
        npRequest.Method = "POST"
        npRequest.ContentType = "application/x-www-form-urlencoded"
        Dim PostVarsString As String = "s=" & sessionID & "&a=" & artist & "&t=" & trackName & "&b=" & album & "&l=" & length & "&n=" & trackNumber & "&m="
        Dim PostVarsEncoding As New System.Text.UTF8Encoding()
        Dim PostVars() As Byte = PostVarsEncoding.GetBytes(PostVarsString)
        npRequest.ContentLength = PostVarsEncoding.GetByteCount(PostVarsString)
        Dim PostStream As System.IO.Stream = npRequest.GetRequestStream()
        PostStream.Write(PostVars, 0, PostVarsString.Length)


        ' Get the response
        Dim npResponse As System.IO.Stream = npRequest.GetResponse.GetResponseStream
        Dim npResponseStreamReader As New System.IO.StreamReader(npResponse, System.Text.Encoding.GetEncoding("utf-8"))
        Dim npResponseText As String = npResponseStreamReader.ReadToEnd()

        ' Parse the response
        Dim npResponseArray As Array = npResponseText.Split(Chr(10))
        Select Case npResponseArray(0)
            Case "BADSESSION"
                MsgBox("Bad Session. Please login again.")
                Return False
            Case "OK"
                Debug.Print("NP Success. " & trackName & " - " & artist)
                Return True
            Case Else
                MsgBox("Unknown Response:" & Chr(10) & npResponseText)
                Return False
        End Select
    End Function
    Public Function Scrobble(ByVal trackName As String, ByVal artist As String, ByVal timestamp As Integer, ByVal source As String, Optional ByVal rating As String = "", Optional ByVal album As String = "", Optional ByVal length As String = "", Optional ByVal trackNumber As String = "")

        ' Make a request
        Dim scrobbleRequest As System.Net.WebRequest = System.Net.WebRequest.Create(submissionURL)
        scrobbleRequest.Method = "POST"
        scrobbleRequest.ContentType = "application/x-www-form-urlencoded"
        Dim PostVarsString As String = "s=" & sessionID & "&a[0]=" & artist & "&t[0]=" & trackName & "&i[0]=" & timestamp & "&o[0]=" & source & "&r[0]=" & rating & "&b[0]=" & album & "&l[0]=" & length & "&n[0]=" & trackNumber & "&m[0]="
        Dim PostVarsEncoding As New System.Text.UTF8Encoding()
        Dim PostVars() As Byte = PostVarsEncoding.GetBytes(PostVarsString)
        scrobbleRequest.ContentLength = PostVarsEncoding.GetByteCount(PostVarsString)
        Dim PostStream As System.IO.Stream = scrobbleRequest.GetRequestStream()
        PostStream.Write(PostVars, 0, PostVarsString.Length)


        ' Get the response
        Dim scrobbleResponse As System.IO.Stream = scrobbleRequest.GetResponse.GetResponseStream
        Dim scrobbleResponseStreamReader As New System.IO.StreamReader(scrobbleResponse, System.Text.Encoding.GetEncoding("utf-8"))
        Dim scrobbleResponseText As String = scrobbleResponseStreamReader.ReadToEnd()

        ' Parse the response
        Dim scrobbleResponseArray As Array = scrobbleResponseText.Split(Chr(10))
        Select Case scrobbleResponseArray(0)
            Case "BADSESSION"
                MsgBox("Bad Session. Please login again.")
                Return False
            Case "OK"
                Debug.Print("Scrobble Success. " & trackName & " - " & artist)
                Return True
            Case Else
                MsgBox("Unknown Response:" & Chr(10) & scrobbleResponseText)
                Return False
        End Select
    End Function
    Public Sub ClearVars()
        sessionID = ""
        npURL = ""
        submissionURL = ""
    End Sub
    Public Function IsReady()
        If npURL.Length > 1 And sessionID.Length > 1 And submissionURL.Length > 1 Then
            Return True
        Else
            Return False
        End If
    End Function
End Class